package com.aji.winecommon.utills;

import com.aji.winepojo.entity.WineAdd;
import com.csvreader.CsvReader;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class SpectrumUtill {
    /**
     * 对数据库查出来的光谱数据做格式修改
     */
    public static List<Float> strToList(String spectrum){
        List<Float> listSpectrum = new ArrayList<>();
        String[] as = spectrum.split(",");
        for (String a:
             as) {
            listSpectrum.add(Float.parseFloat(a));
        }
        return listSpectrum;
    }

    /**
     * 获取光谱信息的x轴
     */
    public static List<Float> getX(String filepath) throws IOException {
        File file = new File(filepath);
        InputStream inputStream = new FileInputStream(file);
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
        CsvReader csvReader = new CsvReader(reader);

        csvReader.readHeaders();
        String line = csvReader.getRawRecord();

        String []lineSplit = line.split(",");

        String[]spectrum = new String[lineSplit.length - 3];
        System.arraycopy(lineSplit, 3, spectrum, 0, lineSplit.length - 3);

        List<Float> listSpectrum = new ArrayList<>();
        for (String s : spectrum) {
            try {
                listSpectrum.add(Float.parseFloat(s.trim()));
            } catch (NumberFormatException e) {
                System.err.println("表头中无法解析为浮点数的值: " + s);
            }
        }

        // 关闭资源
        reader.close();
        inputStream.close();
        return listSpectrum;
    }
}
